package org.hgvc.webapp.ets.spring.service;

import java.util.Date;
import java.util.List;

import org.hgvc.webapp.ets.bo.DocControl;
import org.hgvc.webapp.ets.constant.CommonConstant;
import org.hgvc.webapp.ets.spring.dao.AdminHbmDao;
import org.jocsb.base.bo.Role;
import org.jocsb.base.bo.User;
import org.jocsb.base.bo.UserRole;
import org.jocsb.base.exception.BaseException;
import org.jocsb.base.util.SpringUtils;
import org.jocsb.base.util.SystemUtil;


public class AdminServiceImpl implements AdminService {

	private AdminHbmDao dao;
	private MasterSetupService masterSetupService;

	public void setMasterSetupService(MasterSetupService masterSetupService) {
		this.masterSetupService = masterSetupService;
	}

	public AdminHbmDao getDao() {
		return dao;
	}

	public void setDao(AdminHbmDao dao) {
		this.dao = dao;
	}
	public List<User> getUserList()throws BaseException{
		try{

			List<User> usrList = dao.getObjectList(User.class);
			for(User user:usrList){
				UserRole role = dao.getUserRoleByUserId(user.getUserId());
				user.setRole(role.getRole());
			}
			return usrList;
		}catch(Exception ex){
			ex.printStackTrace();
			throw new BaseException(SpringUtils.getMessage("error.list.user", new Object[]{}));
		}
	}

	public void createUser(User user,User createdUser,String userId)throws BaseException{
		try{

			//validate
			User duplicate = dao.loadUserByUsername(user.getUsername());
			if(duplicate!=null)
				throw new BaseException(SpringUtils.getMessage("error.duplicate.username", new Object[]{}));

			UserRole userrole = new UserRole();
			Role role = new Role();
			role.setRoleId(userId);

			userrole.setRole(role);

			String password = user.getPassword();
			user.setPassword(SystemUtil.generatePassword(user.getUsername(),password));
			user.setCreatedBy(createdUser);
			user.setCreatedDate(new Date());
			user.setStatus(CommonConstant.STATUS_YES);
			dao.save(user);
			userrole.setRole(role);
			userrole.setUser(user);
			userrole.setCreatedBy(createdUser);
			userrole.setCreatedDate(new Date());
			dao.save(userrole);
			dao.flush();
			dao.clear();
		}catch(BaseException ex){
			ex.printStackTrace();
			throw ex;
		}catch(Exception ex){
			ex.printStackTrace();
			throw new BaseException(SpringUtils.getMessage("error.create.user", new Object[]{}));
		}
	}
	
	public void editUser(User user,User createdUser,String roleId)throws BaseException{
		try{

			/*//validate
			User duplicate = dao.loadUserByUsername(user.getUsername());
			if(duplicate!=null)
				throw new BaseException(SpringUtils.getMessage("error.duplicate.username", new Object[]{}));*/

			String password = user.getPassword();
			user.setPassword(SystemUtil.generatePassword(user.getUsername(),password));
			user.setModifiedBy(createdUser);
			user.setModifiedDate(new Date());
			dao.update(user);
			if(!user.getRole().getRoleId().equalsIgnoreCase(roleId)){
				UserRole userrole = dao.getUserRoleByUserId(user.getUserId());
				Role role = new Role();
				role.setRoleId(roleId);
				userrole.setRole(role);
				userrole.setModifiedDate(new Date());
				userrole.setModifiedBy(createdUser);
			}
			dao.flush();
			dao.clear();
		}catch(BaseException ex){
			ex.printStackTrace();
			throw ex;
		}catch(Exception ex){
			ex.printStackTrace();
			throw new BaseException(SpringUtils.getMessage("error.edit.user", new Object[]{}));
		}
	}

	public void changeUserPassword(User user)throws BaseException{
		try{
			String password = user.getPassword();
			user.setPassword(SystemUtil.generatePassword(user.getUsername(),password));
			dao.update(user);
			
		}catch(Exception ex){
			ex.printStackTrace();
			throw new BaseException(SpringUtils.getMessage("error.invoke.method", new Object[]{"changeUserPassword()"}));
		}
	}

	public List<Role> getRoleList()throws BaseException{
		try{
			return dao.getRoleList();
		}catch(Exception ex){
			ex.printStackTrace();
			throw new BaseException(SpringUtils.getMessage("error.list.role", new Object[]{}));
		}
	}

	public void deActiveUser(User user,User actionUser,boolean active) throws BaseException{
		try{
			String flag = new String();
			if(active){
				flag = CommonConstant.STATUS_YES;
			}else{
				flag = CommonConstant.STATUS_NO;
			}
			user.setModifiedBy(actionUser);
			user.setModifiedDate(new Date());
			user.setStatus(flag);
			dao.update(user);
		}catch(Exception ex){
			ex.printStackTrace();
			throw new BaseException(SpringUtils.getMessage("error.deactivate.activate.user", new Object[]{}));
		}
	}
	
	public User createNewUserWithRole(String username,String password,Role role,User createdBy)throws Exception{
		User usr = dao.loadUserByUsername(username);
		if(usr!=null){
			throw new BaseException(SpringUtils.getMessage("error.duplicate.username",new Object[]{}));
		}
		
		//create user
		User newUser = new User();
		newUser.setCreatedBy(createdBy);
		newUser.setCreatedDate(new Date());
		newUser.setUsername(username);
		newUser.setStatus(CommonConstant.STATUS_YES);
		password = SystemUtil.generatePassword(username, password);
		newUser.setPassword(password);
		dao.save(newUser);
		
		//create user role
		UserRole urole = new UserRole();
		urole.setUser(newUser);
		urole.setCreatedBy(createdBy);
		urole.setCreatedDate(new Date());
		urole.setRole(role);
		dao.save(urole);
		
		return newUser;
	}
	
	public void replaceUserRoleWithNewRole(User user,Role newRole,User createdBy )throws Exception{
		
		//delete existing role
		dao.deleteUserRole(user.getUserId());
		
		//inser new role
		UserRole urole = new UserRole();
		urole.setUser(user);
		urole.setCreatedBy(createdBy);
		urole.setCreatedDate(new Date());
		urole.setRole(newRole);
		dao.save(urole);
		
	}

	public synchronized String getDocumentNo(String type)throws BaseException{
		String documentNo="";
		try{
			DocControl docControl = masterSetupService.getDocControlByType(type);
			if (docControl==null)
				throw new BaseException(SpringUtils.getMessage("error.doc.type.not.config", new Object[]{type}));

			StringBuffer numberBuf =new StringBuffer();
			numberBuf.append(docControl.getPrefix().replaceAll("NOPREFIX", ""));
			long counter = docControl.getNumber()+1;
			long currentSize=new Long(String.valueOf(counter).length()).longValue();
			long size = docControl.getSize();
			for (long l=currentSize;l<size;l++){
				numberBuf.append("0");
			}
			numberBuf.append(counter);
			documentNo = numberBuf.toString();
			docControl.setNumber(counter);
			masterSetupService.updateDocControl(docControl);
		}catch(Exception ex){
			ex.printStackTrace();
			throw new BaseException(SpringUtils.getMessage("error.generate.doc.no", new Object[]{type}));
		}
		return documentNo;
	}
	
	public synchronized String getPreDocumentNo(String type)throws BaseException{
		String documentNo="";
		try{
			DocControl docControl = masterSetupService.getDocControlByType(type);
			if (docControl==null)
				throw new BaseException(SpringUtils.getMessage("error.doc.type.not.config", new Object[]{type}));

			StringBuffer numberBuf =new StringBuffer();
			numberBuf.append(docControl.getPrefix().replaceAll("NOPREFIX", ""));
			long counter = docControl.getNumber()+1;
			long currentSize=new Long(String.valueOf(counter).length()).longValue();
			long size = docControl.getSize();
			for (long l=currentSize;l<size;l++){
				numberBuf.append("0");
			}
			numberBuf.append(counter);
			documentNo = numberBuf.toString();
		}catch(Exception ex){
			ex.printStackTrace();
			throw new BaseException(SpringUtils.getMessage("error.generate.doc.no", new Object[]{type}));
		}
		return documentNo;
	}
	
}
